package com.conversationboard.controller;

import java.io.IOException;
import java.security.Principal;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.model.Board;
import com.conversationboard.model.Boards;
import com.conversationboard.model.User;

@WebServlet(name = "BoardsXmlControllerServlet", urlPatterns = "/BoardsXmlControllerServlet")
public class BoardsXmlControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -720841442413684149L;


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {

			Principal principal = request.getUserPrincipal();
			User user = User.getAnonymousUser();

			if (principal != null) {
				user = User.get(principal.getName());
			}

			response.setCharacterEncoding("UTF-8");
			request.setCharacterEncoding("UTF-8");

			List<Board> boards = Boards.getAuthorisedBoards(user, false);
			StringBuilder buffer = new StringBuilder();

			buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");

			buffer.append("<Boards>");

			buffer.append("<URI>");
			buffer.append(request.getContextPath());
			buffer.append("</URI>");

			for (Board board : boards) {
				buffer.append("<Board>");
				buffer.append("<BoardId>" + board.getBoardId() + "</BoardId>");
				buffer.append("<Name>" + board.getName() + "</Name>");
				buffer.append("<Description>" + board.getDescription() + "</Description>");
				buffer.append("<Private>" + board.isPrivateBoard() + "</Private>");
				buffer.append("<Popular>" + board.isPopularBoard() + "</Popular>");
				buffer.append("</Board>");
			}

			buffer.append("</Boards>");

			String xmlData = buffer.toString();

			response.setContentType("text/xml");
			response.getWriter().append(xmlData);

		} catch (SQLException e) {
			throw new ServletException(e);
		}
	}

}
